﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web.Mvc;
using Lion.WeiXin.Core.Message;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
using Lion.WeiXin.Handler;
using System.Web;
using System.Web.Script.Serialization;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.MvcExtension;
namespace Lion.WeiXin.Controllers
{

    public class WeiXinController : Controller
    {
        ///// <summary>
        ///// 接收Post请求，处理，回复请求
        ///// </summary>     
        //public ActionResult Post()
        //{
        //    //微信接入验证GET请求
        //    Tools.Log.LogHelper.Info("请求来自:IP={0},Method={1}", Request.UserHostAddress, Request.HttpMethod);
        //    WeiXinManager weixin = new WeiXinManager();
        //    if (Request.HttpMethod.ToUpper() == "GET")
        //    {
        //        string echostr = Request["echoStr"];
        //        string signature = Request["signature"];
        //        string timestamp = Request["timestamp"];
        //        string nonce = Request["nonce"];
        //        string token = "thisismhsg100";
        //        string result = weixin.FirstValid(echostr, signature, timestamp, nonce, token);
        //        //验证结果推送...不然微信平台无法验证token
        //        Response.Write(result);
        //        Response.End();
        //    }
        //    ////Post请求 使用消息回传
        //    if (Request.HttpMethod.ToUpper() == "POST")
        //    {
        //        try
        //        {
        //            Stopwatch sw = new Stopwatch();
        //            sw.Start();
        //            string result = weixin.AcceptPost(Request.InputStream);
        //            //回复请求
        //            Response.Write(result);
        //            Response.End();
        //            Tools.Log.LogHelper.Info("回复消息:{0}", result);
        //            sw.Stop();
        //            Tools.Log.LogHelper.Info("处理消息总共耗时:{0} 毫秒", sw.ElapsedMilliseconds);


        //        }
        //        catch (Exception ex)
        //        {
        //            Tools.Log.LogHelper.Error(ex, "Post消息处理异常!");
        //        }
        //    }

        //    return View();
        //}

        public WeiXinController()
        {
            _Token = Config.Token;
        }

        string _Token = string.Empty;
        /// <summary>
        /// 微信后台验证地址（使用Get），微信后台的“接口配置信息”的Url填写如：http://weixin.senparc.com/weixin
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature.Check(signature, timestamp, nonce, _Token))
            {
                return Content(echostr);//返回随机字符串则表示验证通过
            }
            else
            {
                return Content("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, _Token));
            }
        }


        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            if (!CheckSignature.Check(signature, timestamp, nonce, _Token))
            {
                LogHelper.Info("Post 参数错误!");
                return Content("参数错误！");
            }

            var messageHandler = new CustomMessageHandler(Request.InputStream);//接收消息

            messageHandler.Execute();//执行微信处理过程
            return new WeixinResult(messageHandler);//返回结果
        }

    }
}
